Skip to content

fix(gemini): keep empty text parts when re-marshaling requests - #8435

Open
RedwindA wants to merge 1 commit into
QuantumNous:mainfrom
RedwindA:fix/gemini-empty-text-part
Open

RedwindA wants to merge 1 commit into
QuantumNous:mainfrom
RedwindA:fix/gemini-empty-text-part

Conversation

@RedwindA

@RedwindA RedwindA commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

English template: .github/PULL_REQUEST_TEMPLATE/en.md

Important

  • 描述可用 AI 辅助。提交前请审阅并精炼全文,仅保留维护者需要复核的要点,并声明对其负责。PR 正文及后续评论均不得直接粘贴未经人工过滤的大段 AI 文本;多次提交此类内容可能会被 block。
  • 开启透传请勿反馈问题;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 请按本模板填写后再提交。

🔗 关联任务 / Related Issue

  • 没有对应 Issue。同类报错见 Gemini转发,CherryStudio报400 #1017(当时出在 system_instruction,后来原生路径会清掉全空的 systemInstruction,但 contents 里的空 part 没有处理)。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

📝 变更描述 / Description

Gemini 原生接口回放历史时,模型输出里常见的空文本尾块 {"text": ""}(开启 thinking + 工具调用时,签名挂在 functionCall 上,尾块就是裸的空 text)经过 new-api 重新序列化后变成 {},上游返回:

GenerateContentRequest.contents[26].parts[4].data: required oneof field 'data' must have one initialized field

原因是 GeminiPart.Text 为 string + omitempty。{"text": "", "thoughtSignature": "..."} 也会被改成 {"thoughtSignature": "..."},同样丢了 text。

修复:给 GeminiPart 加 MarshalJSON,当 text 是唯一的 data 字段时即使为空也输出 "text"。从 JSON 解码时没有 text 成员的 part(例如无法识别的字段)仍然输出 {},让上游报错,而不是悄悄变成空文本。没有把 Text 改成 *string,避免改动所有转换器。

📸 运行证明 / Proof of Work

本地 SQLite 起一个干净实例(go build -o new-api . && ./new-api),建一个 Gemini 类型渠道,Base URL 填 http://127.0.0.1:8081,模型 gemini-2.5-flash,再建一个令牌。上游用下面的脚本(python3 mock_upstream.py 8081),它会打印收到的请求体。

mock_upstream.py
import json, sys
from http.server import BaseHTTPRequestHandler, HTTPServer

RESPONSE = {"candidates": [{"index": 0, "finishReason": "STOP",
                            "content": {"role": "model", "parts": [{"text": "ok"}]}}],
            "usageMetadata": {"promptTokenCount": 12, "candidatesTokenCount": 8, "totalTokenCount": 20}}

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        print(f"{self.command} {self.path}\n{body.decode(errors='replace')}\n", flush=True)
        data = json.dumps(RESPONSE).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data))); self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass

HTTPServer(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()

请求:

curl http://127.0.0.1:3000/v1beta/models/gemini-2.5-flash:generateContent \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{"contents":[
 {"role":"user","parts":[{"text":"What'\''s the weather in Paris?"}]},
 {"role":"model","parts":[
   {"text":"Need to call the tool.","thought":true},
   {"functionCall":{"name":"get_weather","args":{"city":"Paris"}},"thoughtSignature":"c2lnLTE="},
   {"text":""}]},
 {"role":"user","parts":[{"functionResponse":{"name":"get_weather","response":{"temp":18}}}]},
 {"role":"model","parts":[{"text":"It is 18°C."},{"text":"","thoughtSignature":"c2lnLTI="}]},
 {"role":"user","parts":[{"text":"Thanks"}]}]}'

上游收到的两个空 text part(jq -c '[.contents[1].parts[2], .contents[3].parts[1]]'):

  • 修复前(main cb074d31e):[{},{"thoughtSignature":"c2lnLTI="}]
  • 修复后(本 PR 1efdfb593):[{"text":""},{"text":"","thoughtSignature":"c2lnLTI="}]

同一请求里的 thought、带签名的 functionCall、functionResponse 修复前后一致。

另外在 LibreChat + Gemini(thinking + 工具调用)的真实对话里,修复前第二轮(回传工具结果)报上述 400,修复后正常。

单元测试:relaykit/dto/gemini_part_test.go 覆盖各类 part 的解码再编码;common/json_test.go 加了一条走宿主 JSON 编解码 + DeepCopy 的用例(原生路径会经过这两步)。两者在 main 上均失败。

✅ 提交前检查项 / Checklist

  • 人工确认: 无论描述是否由 AI 生成,我已审阅并精炼全文,仅保留可复核的要点,并声明对其准确性与完整性负责。PR 正文及后续评论均未直接粘贴未经人工过滤的大段 AI 文本。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • 新功能关联 Issue: 若此 PR 标记为 New feature,我已关联对应 Issue;若尚无 Issue,我已先自行创建。
  • 事前沟通: 若改动较大或涉及方向性变更,已在关联 Issue 中与维护者沟通并达成一致。
  • 功能范围: 本 PR 不是 Coding Plan、逆向渠道、第三方封装接口,也不是对 Codex 渠道类型的改动。
  • 非透传: 本 PR 不是针对开启透传后的转发行为;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 范围聚焦: 本 PR 为一项聚焦改动,未包含无关代码。
  • 本地验证: 已按变更路径实际验证,并写明命令与观察结果。仅声明 go build 通过或测试通过,不视为有效证明。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

Summary by CodeRabbit

  • Bug Fixes
    • Gemini content now more reliably survives JSON round trips, including explicitly empty text parts and thought metadata.
    • Function calls and responses, inline and file data, and trailing empty text parts are preserved across supported round trips.
    • Empty or unrecognized content is serialized consistently, and inline-data keys are normalized.

GeminiPart.Text is a string with omitempty, so a replayed closing chunk
{"text": ""} was re-marshaled as {}. Gemini treats Part.data as a oneof
and rejects such a part with "required oneof field 'data' must have one
initialized field".

GeminiPart now emits "text" when it is the only data field, except for
parts decoded from JSON without a text member, which still marshal as {}
so unrecognized content fails upstream instead of becoming empty text.
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

GeminiPart now tracks whether decoded JSON omitted the text member. Its custom marshaler uses this state and the part’s other fields to determine whether to emit an empty text value. New tests cover part and request round trips.

Changes

Gemini text round trips

Layer / File(s) Summary
Presence-aware GeminiPart serialization
relaykit/dto/gemini.go
GeminiPart records whether decoded JSON omitted text. Custom marshaling uses that state and other part data to select its serialization behavior.
Round-trip validation
relaykit/dto/gemini_part_test.go, common/json_test.go
Tests cover GeminiPart and GeminiChatRequest round trips, including empty text, thought metadata, function calls and responses, inline data, and file data.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: calcium-ion

Merge Risk: Minimal · up to 1efdf

This fixes Gemini request replay for parts that contain an empty text value, so those requests are no longer rejected. The behavior is narrow and covered by tests, and no merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: Gemini requests keep empty text parts when they are re-marshaled. The raw summary shows GeminiPart gains custom marshaling that preserves an explicit empty text field …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: Gemini requests keep empty text parts when they are re-marshaled. The raw summary shows GeminiPart gains custom marshaling that preserves an explicit empty text field when text is the only data, and tests cover this behavior. The title uses the conventional fix(scope) form and is specific, so a teammate scanning history can identify the primary change.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the JSON trail
An empty text can still prevail
Thought signatures pass in line
Parts return in ordered time
The rabbit hops; the fields align

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9f6fe92f-331c-4245-adfb-72b631c28d58
Commits

Reviewing files that changed from the base of the PR and between cb074d3 and 1efdfb5.

Files selected for processing: 3

  • common/json_test.go
  • relaykit/dto/gemini.go
  • relaykit/dto/gemini_part_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant